﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Data;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace VoteList.Layouts.VoteList
{
    public partial class VotePage : LayoutsPageBase
    {
        public static string Message = string.Empty;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //TextBox3.Text = SPContext.Current.Web.CurrentUser.LoginName;
                // Populate the repeater control with the Items DataSet
                PagedDataSource objPds = new PagedDataSource();
                objPds.DataSource = GetCandidates().DefaultView;

                // Indicate that the data should be paged
                objPds.AllowPaging = true;

                // Set the number of items you wish to display per page
                objPds.PageSize = Define.PAGESIZE;

                // Set the PagedDataSource's current page
                objPds.CurrentPageIndex = CurrentPage;

                lblCurrentPage.Text = "Page: " + (CurrentPage + 1).ToString() + " of "
            + objPds.PageCount.ToString();

                // Disable Prev or Next buttons if necessary
                CmdPrev.Enabled = !objPds.IsFirstPage;
                CmdNext.Enabled = !objPds.IsLastPage;

                repeaterItems.DataSource = objPds;
                repeaterItems.DataBind();
            }
        }

        public int CurrentPage
        {
            get
            {
                // look for current page in ViewState
                object o = this.ViewState["_CurrentPage"];
                if (o == null)
                    return 0; // default page index of 0
                else
                    return (int)o;
            }

            set
            {
                this.ViewState["_CurrentPage"] = value;
            }
        }


        Dictionary<string, bool> StatusDic
        {
            get
            {
                if (ViewState["_StatusDic"] == null)
                {
                    ViewState["_StatusDic"] = new Dictionary<string, bool>();
                }

                return (Dictionary<string, bool>)ViewState["_StatusDic"];
            }

            set
            {
                ViewState["_StatusDic"] = value;
            }
        }

        //Remember the station of checked CheckBox in all pages         
        public void RememberOldValues(Dictionary<string, bool> dic)
        {
            foreach (RepeaterItem rpItem in repeaterItems.Items)
            {
                CheckBox chkbx = rpItem.FindControl("chkbx") as CheckBox;
                if (chkbx.Checked && !dic.Keys.Contains(chkbx.Text))
                {
                    dic.Add(chkbx.Text, true);
                }

                if (!chkbx.Checked && dic.Keys.Contains(chkbx.Text))
                {
                    dic.Remove(chkbx.Text);
                }
            }
        }

        //Repopulate the station of every CheckBox in all pages31  
        public void RePopulateValues(Dictionary<string, bool> dic)
        {
            foreach (RepeaterItem rpItem in repeaterItems.Items)
            {
                CheckBox chkbx = rpItem.FindControl("chkbx") as CheckBox;
                if (dic.Keys.Contains(chkbx.Text) && dic[chkbx.Text] == true)
                {
                    chkbx.Checked = true;
                }
            }
        }

        public void cmdPrev_Click(object sender, System.EventArgs e)
        {
            // Set viewstate variable to the previous page
            CurrentPage -= 1;

            //RememberOldValues(StatusDic);

            // Reload control
            ItemsGet();

            //RePopulateValues(StatusDic);
        }

        public void cmdNext_Click(object sender, System.EventArgs e)
        {
            // Set viewstate variable to the next page
            CurrentPage += 1;

            //RememberOldValues(StatusDic);

            // Reload control
            ItemsGet();

            //RePopulateValues(StatusDic);
        }

        public void FirstPage_click(object sender, System.EventArgs e)
        {
            CurrentPage = 0;
            ItemsGet();
        }

        public void LastPage_click(object sender, System.EventArgs e)
        {
            DataTable dt = GetCandidates();

            CurrentPage = dt.Rows.Count / Define.PAGESIZE;

            ItemsGet();
        }

        public static void ShowDialog(Page page, string message)
        {
            try
            {
                Message = message;

                string csname = "ShowDialogScript";
                Type cstype = page.ClientScript.GetType();
                ClientScriptManager cs = page.ClientScript;
                if (!cs.IsStartupScriptRegistered(cstype, csname))
                {
                    StringBuilder js = new StringBuilder();
                    js.Append("<script type='text/javascript'>");
                    js.Append("ExecuteOrDelayUntilScriptLoaded(openDialog, 'sp.ui.dialog.js');");
                    js.Append("</script>");
                    cs.RegisterStartupScript(cstype, csname, js.ToString());
                }
            }
            catch { }
        }


        private void ItemsGet()
        {
            // Populate the repeater control with the Items DataSet
            PagedDataSource objPds = new PagedDataSource();
            objPds.DataSource = GetCandidates().DefaultView;
            objPds.AllowPaging = true;
            objPds.PageSize = Define.PAGESIZE;

            objPds.CurrentPageIndex = CurrentPage;

            lblCurrentPage.Text = "Page: " + (CurrentPage + 1).ToString() + " of "
               + objPds.PageCount.ToString();

            // Disable Prev or Next buttons if necessary
            CmdPrev.Enabled = !objPds.IsFirstPage;
            CmdNext.Enabled = !objPds.IsLastPage;

            repeaterItems.DataSource = objPds;
            repeaterItems.DataBind();
        }

        protected void DoVote(object sender, EventArgs e)
        {

            string accountName = ((ImageButton)sender).CommandArgument;

            SPListItem item = null;
            string mVote = string.Empty;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                {
                    using (SPWeb web = site.RootWeb)
                    {
                        SPList list = web.Lists[Define.DATALISTNAME];


                        item = GetVoteListItem(list, SPContext.Current.Web.CurrentUser);

                        if (item == null)
                        {
                            item = AddVoteListItem(false);
                        }

                        if (item != null)
                        {
                            mVote = string.Format("{0};{1}|", accountName, DateTime.Now.ToString());

                            int votesRemain = VotesRemain(item);

                            if (votesRemain == 2)
                            {
                                AddListItemVote(item, mVote);
                                ShowDialog(Page, string.Format("您给{0}投了一票", accountName));
                            }
                            else if (votesRemain == 1)
                            {
                                if (IsVoteTheSamePerson(item, accountName + ";"))
                                {
                                    //不允许给同一个人投两票
                                    ShowDialog(Page, "不允许给同一个人投两票");
                                }
                                else
                                {
                                    AddListItemVote(item, mVote);
                                    ShowDialog(Page, string.Format("您给{0}投了一票", accountName));
                                }
                            }
                            else
                            {
                                ShowDialog(Page, "您已经投了两票，不允许再投票");
                            }
                        }

                    }
                }
            });

            ItemsGet();
        }

        //need update
        public int VotesRemain(SPListItem item)
        {
            string voteInfo = item[Define.COLUMN_VOTE] != null ? item[Define.COLUMN_VOTE].ToString() : string.Empty;

            if (string.IsNullOrEmpty(voteInfo))
            {
                return 2;
            }

            int splitCount = voteInfo.Split(';').Length;

            if (splitCount >= 3)
            {
                return 0;
            }
            else if (splitCount == 2)
            {
                return 1;
            }

            return 0;
        }

        public bool IsVoteTheSamePerson(SPListItem item, string loginName)
        {
            string voteInfo = item[Define.COLUMN_VOTE] != null ? item[Define.COLUMN_VOTE].ToString() : string.Empty;

            if (voteInfo.Contains(loginName))
            {
                return true;
            }

            return false;
        }

        public SPListItem AddVoteListItem(bool isCandidate)
        {
            SPListItem item = null;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                {
                    using (SPWeb web = site.RootWeb)
                    {
                        SPList list = web.Lists[Define.DATALISTNAME];
                        if (list != null)
                        {
                            item = list.AddItem();

                            item[Define.COLUMN_TITLE] = SPContext.Current.Web.CurrentUser.Name;
                            item[Define.DATACOLUMN_ACCOUNT] = SPContext.Current.Web.CurrentUser;
                            item[Define.COLUMN_ISCANDIDATE] = isCandidate;
                            //item["DesignDes"] = "test";

                            item.Update();
                            list.Update();
                        }
                    }
                }
            });

            return item;
        }

        public void AddListItemVote(SPListItem item, string vote)
        {
            string voteInfo = item[Define.COLUMN_VOTE] != null ? item[Define.COLUMN_VOTE].ToString() : string.Empty;

            item[Define.COLUMN_VOTE] = voteInfo + vote;

            item.Update();
        }

        public SPListItem GetVoteListItem(SPList list, SPUser user)
        {
            SPQuery query = new SPQuery();

            query.Query = "<Where><Eq><FieldRef Name=\"Account\" LookupId=\"TRUE\" /><Value Type=\"User\">" + user.ID + "</Value></Eq></Where>";

            SPListItemCollection itemCollection = list.GetItems(query);

            if (itemCollection.Count > 0)
            {
                return itemCollection[0];
            }
            else
            {
                return null;
            }
        }

        public int GetVoteNum(string loginName)
        {
            SPWeb web = SPContext.Current.Site.RootWeb;

            SPList list = web.Lists[Define.DATALISTNAME];

            int count = 0;

            foreach (SPListItem item in list.Items)
            {
                if (item[Define.COLUMN_VOTE] != null && item[Define.COLUMN_VOTE].ToString().Contains(loginName + ";"))
                {
                    count++;
                }
            }

            return count;
        }

        /// <summary>
        /// GetUser from SPUserField
        /// </summary>
        /// <param name="list">SPList</param>
        /// <param name="filedName">String</param>
        /// <param name="value">String</param>
        /// <returns>SPUser</returns>
        public SPUser GetSPUserFromID(SPList list, string filedName, string value)
        {
            SPFieldUser userField = (SPFieldUser)list.Fields[filedName]; ;

            SPFieldUserValue fieldValue = (SPFieldUserValue)userField.GetFieldValue(value);

            SPUser user = fieldValue.User;

            return user;
        }
        private string EnsureName(string loginName)
        {
            string name = string.Empty;
            SPUser user = SPContext.Current.Web.EnsureUser(loginName);
            if (user != null)
            {
                name = user.Name;
            }
            return name;
        }

        public string GetLoginNameWithoutDomain(string loginName)
        {
            int index = loginName.IndexOf("\\");

            if (index > -1)
            {
                loginName = loginName.Substring(index + 1);
            }

            return loginName;
        }

        public string GetVarObj(string loginName)
        {
            int index = loginName.LastIndexOf("-");

            if (index > -1)
            {
                loginName = loginName.Substring(index + 1);
            }

            int index2 = loginName.IndexOf("\\");

            if (index2 > -1)
            {
                loginName = loginName.Substring(index2 + 1);
            }

            return loginName;
        }

        public string GetComments(string loginName)
        {
            StringBuilder mStrBuilder = new StringBuilder();

            SPWeb web = SPContext.Current.Web;

            SPList list = web.Lists[Define.commentmessage];
            SPQuery query = new SPQuery();
            string comment = string.Empty;
            string commentor = string.Empty;
            query.Query = @"<Where><Eq><FieldRef Name='To' /><Value Type='Text'>" + loginName + "</Value></Eq></Where><OrderBy><FieldRef Name='Created' Ascending='TRUE' /></OrderBy>";

            SPListItemCollection itemCollection = list.GetItems(query);
            foreach (SPListItem item in itemCollection)
            {
                try
                {
                    string lName = item["From"].ToString();
                    string name = EnsureName(lName);
                    if (string.IsNullOrEmpty(name))
                    {
                        commentor = lName;
                    }
                    else
                    {
                        commentor = name;
                    }
                    comment = item["Title"] != null ? Server.HtmlEncode(item["Title"].ToString()).Replace("\r", "").Replace("\n", "") : string.Empty;

                    mStrBuilder.Append(string.Format("{0}.insertComment(\"{1}\", \"{2}\", \"{3}\");", GetVarObj(loginName), comment, commentor,item.ID));
                    //mStrBuilder.Append(" 说：");
                    //mStrBuilder.Append(item["Title"].ToString());
                    mStrBuilder.Append("\r\n");
                }
                catch { }
            }

            return mStrBuilder.ToString();
        }
        public string GetImageUrl(string loginName)
        {
            SPWeb web = SPContext.Current.Site.RootWeb;
            SPList picList = web.Lists.TryGetList(Define.PICLISTNAME);

            int index = loginName.IndexOf('\\');

            if (index > -1)
            {
                loginName = loginName.Substring(index + 1);
            }

            if (picList != null)
            {
                foreach (SPListItem item in picList.Items)
                {
                    if (item.Name.Contains(loginName))
                    {
                        return web.Url + "/" + item.Url;
                    }
                }
            }

            //return "/_layouts/VoteList/Images/photo.jpg";
            return GetRandomDefaultPhotoURL();
        }

        /// <summary>
        /// Get one of the default photo Url
        /// </summary>
        /// <returns>Url</returns>
        private string GetRandomDefaultPhotoURL()
        {
            Random rnd = new Random();
            int rndNum = rnd.Next(1, 4);
            string strPhotoUrl = string.Empty;
            switch (rndNum)
            {
                case 1:
                    strPhotoUrl = "/_layouts/VoteList/Images/DefaultImage01.png";
                    break;
                case 2:
                    strPhotoUrl = "/_layouts/VoteList/Images/DefaultImage02.png";
                    break;
                case 3:
                    strPhotoUrl = "/_layouts/VoteList/Images/DefaultImage03.png";
                    break;
                case 4:
                    strPhotoUrl = "/_layouts/VoteList/Images/DefaultImage04.png";
                    break;
                default:
                    strPhotoUrl = "/_layouts/VoteList/Images/DefaultImage01.png";
                    break;
            }
            return strPhotoUrl;
        }

        public string GetJSText(string loginName, string des, string comments)
        {
            StringBuilder jsTextBuilder = new StringBuilder();

            jsTextBuilder.Append("<script type=\"text/javascript\">");

            jsTextBuilder.Append(string.Format("var {0} = new singlePerson('{2}', '{1}');", GetVarObj(loginName), des, loginName));
            jsTextBuilder.Append(string.Format(comments));

            jsTextBuilder.Append("</script>");

            return jsTextBuilder.ToString();
        }

        /// <summary>
        /// Get all Candidates
        /// </summary>
        /// <returns>DataTable</returns>
        public DataTable GetCandidates()
        {

            DataTable dt = new DataTable();

            DataColumn column = new DataColumn(Define.DATACOLUMN_NAME);
            DataColumn column1 = new DataColumn(Define.DATACOLUMN_VOTES);
            DataColumn column2 = new DataColumn(Define.DATACOLUMN_LOCATION);
            DataColumn column3 = new DataColumn(Define.DATACOLUMN_DESIGNDES);
            DataColumn column4 = new DataColumn(Define.DATACOLUMN_ACCOUNT);
            DataColumn column5 = new DataColumn(Define.DATACOLUMN_PICURL);
            DataColumn column6 = new DataColumn(Define.DATACOLUMN_COMMENTS);

            //DataColumn column7 = new DataColumn(Define.DATACOLUMN_JS);

            dt.Columns.Add(column);
            dt.Columns.Add(column1);
            dt.Columns.Add(column2);
            dt.Columns.Add(column3);
            dt.Columns.Add(column4);
            dt.Columns.Add(column5);
            dt.Columns.Add(column6);
            //dt.Columns.Add(column7);

            SPWeb web = SPContext.Current.Site.RootWeb;

            SPList list = web.Lists[Define.DATALISTNAME];

            SPQuery query = new SPQuery();

            query.Query = @"<Where><Eq><FieldRef Name='IsCandidate' /><Value Type='Integer'>1</Value></Eq></Where>";

            SPListItemCollection itemCollection = list.GetItems(query);

            string name = string.Empty;
            string location = string.Empty;
            string votes = string.Empty;
            string des = string.Empty;
            string account = string.Empty;
            SPUser tempUser = null;

            foreach (SPListItem item in itemCollection)
            {
                try
                {
                    name = item[Define.COLUMN_TITLE] != null ? item[Define.COLUMN_TITLE].ToString() : string.Empty;
                    location = item[Define.DATACOLUMN_LOCATION] != null ? item[Define.DATACOLUMN_LOCATION].ToString() : string.Empty;
                    if (item[Define.DATACOLUMN_ACCOUNT] != null)
                    {
                        tempUser = GetSPUserFromID(list, Define.DATACOLUMN_ACCOUNT, item[Define.DATACOLUMN_ACCOUNT].ToString());
                        account = tempUser.LoginName;
                        votes = GetVoteNum(tempUser.LoginName).ToString();
                    }
                    else
                    {
                        votes = "0";
                    }

                    des = item[Define.DATACOLUMN_DESIGNDES] != null ? item[Define.DATACOLUMN_DESIGNDES].ToString() : string.Empty;

                    if (string.IsNullOrEmpty(des))
                    {
                        des = "这位同事可能太忙，还没有填写工位描述。";
                    }

                    des = Server.HtmlEncode(des).Replace("\r", "").Replace("\n", "");

                    dt.Rows.Add(name, votes, location, des, account, GetImageUrl(tempUser.LoginName), GetJSText(tempUser.LoginName, des, GetComments(tempUser.LoginName)));
                }
                catch (Exception ex)
                {

                }
            }

            return dt;
        }
    }
}
